package cn.wzptsoft.config;

import cn.wzptsoft.tinymallbe.interceptor.LoginInterceptor;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.InterceptorRegistration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

/**
 * WebMvcConfigurer接口
 * 2.1 addInterceptors：拦截器
 * 2.2 addViewControllers：页面跳转
 * 2.3 addResourceHandlers：静态资源
 * 2.4 configureDefaultServletHandling：默认静态资源处理器
 * 2.5 configureViewResolvers：视图解析器
 * 2.6 configureContentNegotiation：配置内容裁决的一些参数
 * 2.7 addCorsMappings：跨域
 * 2.8 configureMessageConverters：信息转换器
 * <br />
 * <a href="https://blog.csdn.net/zhaokuner/article/details/111227261">WebMvcConfigurer类的模板</a>
 * <a href="http://www.manongjc.com/detail/17-bdbkrdocikwfvja.html">WebMvcConfigurer类的用法</a>
 */
@Configuration
public class WebMvcConfig implements WebMvcConfigurer {

    private final LoginInterceptor loginInterceptor;

    public WebMvcConfig(LoginInterceptor loginInterceptor) {
        this.loginInterceptor = loginInterceptor;
    }

    /**
     * 跨域配置
     */
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        // 允许指定的pathPattern可以进行跨域请求
        registry.addMapping("/**")
                .allowedOriginPatterns("*")
                // 设置浏览器是否需要发送认证信息
                .allowCredentials(true)
                // 设置允许的跨域请求动作，设置为"*"表示允许所有
                // 默认设置为允许简单动作，包括GET POST HEAD
                .allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS")
                // 设置客户端保存pre-flight request缓存的时间
                // pre-flight request 预检请求
                .maxAge(3600);
    }

    /**
     * 拦截器
     */
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        InterceptorRegistration registration = registry.addInterceptor(loginInterceptor);
        // 给拦截器拦截的pathPattern
        registration.addPathPatterns("/user/**");
        registration.addPathPatterns("/address/**");
        registration.addPathPatterns("/order/**");
    }
}
